package com.ruoyi.api.apkVersion.controller;

import com.ruoyi.api.apkVersion.entity.*;
import com.ruoyi.api.apkVersion.service.ApkVersionService;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.result.ResultEnum;
import com.ruoyi.result.ResultView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 说明：APK版本管理
 * 作者：FH Admin QQ313596790
 * 时间：2020-05-25
 */
@Controller
public class ApkVersionController extends BaseController {

  @Autowired
  private ApkVersionService apkversionService;

  @Value("${ruoyi.profile}")
  private String uploadDir;

  @GetMapping("/apkversion/list")
  public String listPage()
  {
    return "apkversion/apkversion_list";
  }

  @GetMapping("/apkversion/edit")
  public String editPage()
  {
    return "apkversion/apkversion_edit";
  }

  @GetMapping("/apkversion/add")
  public String addPage()
  {
    return "apkversion/apkversion_edit";
  }


  /**
   * 保存
   *
   * @param
   * @throws Exception
   */
  @RequestMapping(value = "/api/apkversion/add")
//	@RequiresPermissions("apkversion:add")
  @ResponseBody
  public Object add() throws Exception {
    Map
      <String, Object> map = new HashMap
      <String, Object>();
    String errInfo = "success";
    PageData pd = new PageData();
    pd = this.getPageData();
    pd.put("APKVERSION_ID", this.get32UUID());  //主键
    apkversionService.save(pd);
    map.put("result", errInfo);
    return ResultView.ok(map);
  }

  /**
   * 删除
   *
   * @throws Exception
   */
  @RequestMapping(value = "/api/apkversion/delete")
//	@RequiresPermissions("apkversion:del")
  @ResponseBody
  public Object delete() throws Exception {
    Map
      <String, String> map = new HashMap
      <String, String>();
    String errInfo = "success";
    PageData pd = new PageData();
    pd = this.getPageData();
    apkversionService.delete(pd);
    map.put("result", errInfo);        //返回结果
    return map;
  }

  /**
   * 修改
   *
   * @param
   * @throws Exception
   */
  @RequestMapping(value = "/api/apkversion/edit")
//	@RequiresPermissions("apkversion:edit")
  @ResponseBody
  public Object edit() throws Exception {
    Map
      <String, Object> map = new HashMap
      <String, Object>();
    String errInfo = "success";
    PageData pd = new PageData();
    pd = this.getPageData();
    apkversionService.edit(pd);
    map.put("result", errInfo);
    return ResultView.ok(map);
  }

  /**
   * 列表
   *
   * @param page
   * @throws Exception
   */
  @RequestMapping(value = "/api/apkversion/list")
//	@RequiresPermissions("apkversion:list")
  @ResponseBody
  public Object list(Page page) throws Exception {
    Map
      <String, Object> map = new HashMap
      <String, Object>();
    String errInfo = "success";
    PageData pd = new PageData();
    pd = this.getPageData();
    String KEYWORDS = pd.getString("KEYWORDS");            //关键词检索条件
    if (Tools.notEmpty(KEYWORDS)) pd.put("KEYWORDS", KEYWORDS.trim());
    page.setPd(pd);
    List
      <PageData> varList = apkversionService.list(page); //列出ApkVersion列表
    map.put("varList", varList);
    map.put("page", page);
    map.put("result", errInfo);
    return ResultView.ok(map);
  }

  @RequestMapping(value = "/api/apkversion/updateCheck")
//	@RequiresPermissions("apkversion:list")
  @ResponseBody
  public Object updateCheck() throws Exception {
    Map<String, Object> map = new HashMap<String, Object>();
    String errInfo = "success";
    PageData pd = new PageData();
    pd = this.getPageData();
    String plat1 = pd.getString("PLAT");
    if (StringUtils.isEmpty(plat1)) {
      return ResultView.error(ResultEnum.CODE_2);
    }
    PageData pageData = apkversionService.updateCheck(plat1);
    return ResultView.ok(pageData);
  }
  /**
   * 去修改页面获取数据
   *
   * @param
   * @throws Exception
   */
  @RequestMapping(value = "/api/apkversion/goEdit")
//  @RequiresPermissions("apkversion:edit")
  @ResponseBody
  public Object goEdit() throws Exception {
    Map
      <String
        , Object> map = new HashMap
      <String
        , Object>();
    String errInfo = "success";
    PageData pd = new PageData();
    pd = this.getPageData();
    pd = apkversionService.findById(pd); //根据ID读取
    map.put("pd", pd);
    map.put("result", errInfo);
    return ResultView.ok(map);
  }

  /**
   * 批量删除
   *
   * @param
   * @throws Exception
   */
  @RequestMapping(value = "/api/apkversion/deleteAll")
//  @RequiresPermissions("apkversion:del")
  @ResponseBody
  public Object deleteAll() throws Exception {
    Map
      <String
        , Object> map = new HashMap
      <String
        , Object>();
    String errInfo = "success";
    PageData pd = new PageData();
    pd = this.getPageData();
    String DATA_IDS = pd.getString("DATA_IDS");
    if (Tools.notEmpty(DATA_IDS)) {
      String ArrayDATA_IDS[] = DATA_IDS.split(",");
      apkversionService.deleteAll(ArrayDATA_IDS);
      errInfo = "success";
    } else {
      errInfo = "error";
    }
    map.put("result", errInfo); //返回结果
    return map;
  }



  @RequestMapping(value = "/api/apkversion/apkUpload")
  @ResponseBody
  public Object uploadPro(@RequestParam("file") MultipartFile file) {
    Map<String, Object> map = new HashMap<String, Object>();
    String errInfo = "success";
    if (null != file && !file.isEmpty()) {
      String fileOriginalFilename = file.getOriginalFilename();
      if(fileOriginalFilename.lastIndexOf(".") >= 0){
        fileOriginalFilename=fileOriginalFilename.substring(0,fileOriginalFilename.lastIndexOf("."));
      }
      String fileOutputName=fileOriginalFilename.trim()+System.currentTimeMillis();
      String filePath = uploadDir + "/apk/";    //文件上传路径
      String fileName = FileUpload.fileUp(file, filePath, fileOutputName);    //执行上传
      map.put("fileName",fileName);
    }
    map.put("result", errInfo);        //返回结果
    return ResultView.ok(map);
  }

  @RequestMapping(value = "/api/apkversion/apkDownload")
  public void download(
    @RequestParam("fileName") String filename
  ) throws IOException {
    ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletResponse response = requestAttributes.getResponse();
    // 设置信息给客户端不解析
    String type = new MimetypesFileTypeMap().getContentType(filename);
    // 设置contenttype，即告诉客户端所发送的数据属于什么类型
    response.setHeader("Content-type",type);
//    response.setHeader();"Content-Length", String.valueOf(bis.available());
    response.setContentType("application/force-download");
    // 设置编码
    String hehe = new String(filename.getBytes("utf-8"), "iso-8859-1");
    // 设置扩展头，当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。
    response.setHeader("Content-Disposition", "attachment;filename=" + hehe);
    File file = new File(uploadDir + "/apk/"+filename);
    if(file.exists()){
      response.setHeader("Content-Length",String.valueOf(file.length()));
      OutputStream outputStream = response.getOutputStream();
      byte[] buff = new byte[1024];
      BufferedInputStream bis = null;
      // 读取filename
      bis = new BufferedInputStream(new FileInputStream(file));
      int i = bis.read(buff);
      while (i != -1) {
        outputStream.write(buff, 0, buff.length);
        outputStream.flush();
        i = bis.read(buff);
      }
    }
  }
  /**
   * 分享下载链接
   */
  @PostMapping("/api/apk/generateShareLinkUrl")
  @ResponseBody
  public ResultView generateShareLinkUrl(String plat)
  {
    PageData pageData=null;
    if(!StringUtils.isEmpty(plat) && plat.equalsIgnoreCase("2")){
      pageData = apkversionService.updateCheck("2");
    }else{
      pageData=apkversionService.updateCheck("1");
    }
    String FILENAME=(String)pageData.get("FILENAME");
    String url= Global.getAdminUrl()+"/api/apkversion/apkDownload?fileName="+FILENAME;
    return ResultView.ok(url);
  }

}
